import { defineStore } from "pinia";
import { api } from "@/utils/api";

export const useArticleMultipleStore = defineStore('articleMultiple', {
    persist: true,
    state: () => ({
        categories: {} as Record<string, {
            currentPage: number;
            pageSize: number;
            currentArticleIndex: number;
            articleList: Article[];
            articleListForPrevNext: [ArticleRecord[], ArticleRecord[], ArticleRecord[]];
        }>,
    }),
    actions: {
        setCategories(categoryNames: string[]) {
            categoryNames.forEach(categoryName => {
                if (!this.categories[categoryName]) {
                    this.categories[categoryName] = {
                        currentPage: 1,
                        pageSize: 10,
                        currentArticleIndex: 0,
                        articleList: [],
                        articleListForPrevNext: [[], [], []],
                    };
                }
            });
        },
        async loadArticles(categoryName: string, page: number) {
            const category = this.categories[categoryName];
            if (!category) return;

            category.articleList = [];

            const response = await api.getNewsCenterPage(categoryName, page, category.pageSize);
            if (response && response.code === 1) {
                const articles: Article[] = response.data.content.map((article: Article) => ({
                    id: article.id,
                    title: article.title,
                    createBy: article.createBy,
                    updateBy: article.updateBy,
                    createTime: article.createTime,
                    updateTime: article.updateTime,
                    type: article.type,
                    type2: article.type2,
                    pic: article.pic,
                    pdfFileName: article.pdfFileName,
                    details: article.details,
                }));
                category.articleList = articles;
                category.articleListForPrevNext[1] = articles;
                category.currentPage = page;
            }
        },
        async setCurrentArticleIndex(categoryName: string, articleId: number) {
            const category = this.categories[categoryName];
            if (!category) return;

            let index = category.articleList.findIndex((article) => article.id === articleId);
            if (index === -1) {
                const prevPageResponse = await api.getNewsCenterPage(categoryName, category.currentPage - 1, category.pageSize);
                const nextPageResponse = await api.getNewsCenterPage(categoryName, category.currentPage + 1, category.pageSize);

                if (prevPageResponse.code === 1) {
                    const prevArticles = prevPageResponse.data.content;
                    index = prevArticles.findIndex((article: Article) => article.id === articleId);
                    if (index !== -1) {
                        category.articleList = prevArticles;
                        category.currentPage -= 1;
                        category.currentArticleIndex = index;
                        return;
                    }
                }

                if (nextPageResponse.code === 1) {
                    const nextArticles = nextPageResponse.data.content;
                    index = nextArticles.findIndex((article: Article) => article.id === articleId);
                    if (index !== -1) {
                        category.articleList = nextArticles;
                        category.currentPage += 1;
                        category.currentArticleIndex = index;
                        return;
                    }
                }

                console.error("Article not found in adjacent pages");
            } else {
                category.currentArticleIndex = index;
            }
        },
        async loadPrevNextPages(categoryName: string) {
            const category = this.categories[categoryName];
            if (!category) return;

            if (category.currentArticleIndex === 0 && category.currentPage > 1) {
                const response = await api.getNewsCenterPage(categoryName, category.currentPage - 1, category.pageSize);
                if (response && response.code === 1) {
                    category.articleListForPrevNext[0] = response.data.content.map((article: Article) => ({
                        id: article.id,
                        title: article.title,
                    }));
                }
            }

            if (category.currentArticleIndex === category.articleList.length - 1 && category.articleList.length === category.pageSize) {
                const response = await api.getNewsCenterPage(categoryName, category.currentPage + 1, category.pageSize);
                if (response && response.code === 1) {
                    category.articleListForPrevNext[2] = response.data.content.map((article: Article) => ({
                        id: article.id,
                        title: article.title,
                    }));
                }
            }
        },
        async peekPreviousArticle(categoryName: string): Promise<ArticleRecord | null> {
            const category = this.categories[categoryName];
            if (!category) return null;

            let tempIndex = category.currentArticleIndex;
            let tempPage = category.currentPage;

            if (tempIndex === 0 && tempPage > 1) {
                const response = await api.getNewsCenterPage(categoryName, tempPage - 1, category.pageSize);
                if (response && response.code === 1) {
                    const articles: Article[] = response.data.content;
                    return articles[articles.length - 1] || null;
                }
            } else if (tempIndex > 0) {
                return category.articleList[tempIndex - 1] || null;
            }
            return null;
        },
        async peekNextArticle(categoryName: string): Promise<ArticleRecord | null> {
            const category = this.categories[categoryName];
            if (!category) return null;

            let tempIndex = category.currentArticleIndex;
            let tempPage = category.currentPage;

            if (tempIndex === category.articleList.length - 1) {
                const response = await api.getNewsCenterPage(categoryName, tempPage + 1, category.pageSize);
                if (response && response.code === 1 && response.data.content.length > 0) {
                    const articles: Article[] = response.data.content;
                    return articles[0] || null;
                }
            } else if (tempIndex < category.articleList.length - 1) {
                return category.articleList[tempIndex + 1] || null;
            }
            return null;
        },
        async getPreviousArticle(categoryName: string): Promise<ArticleRecord | null> {
            const category = this.categories[categoryName];
            if (!category) return null;

            if (category.currentArticleIndex === 0 && category.currentPage > 1) {
                await this.loadArticles(categoryName, category.currentPage - 1);
                category.currentArticleIndex = category.articleList.length - 1;
                return category.articleList[category.currentArticleIndex] || null;
            } else if (category.currentArticleIndex > 0) {
                category.currentArticleIndex -= 1;
                return category.articleList[category.currentArticleIndex];
            }
            return null;
        },
        async getNextArticle(categoryName: string): Promise<ArticleRecord | null> {
            const category = this.categories[categoryName];
            if (!category) return null;

            if (category.currentArticleIndex === category.articleList.length - 1) {
                await this.loadArticles(categoryName, category.currentPage + 1);
                category.currentArticleIndex = 0;
                return category.articleList[category.currentArticleIndex] || null;
            } else if (category.currentArticleIndex < category.articleList.length - 1) {
                category.currentArticleIndex += 1;
                return category.articleList[category.currentArticleIndex];
            }
            return null;
        },
    },
});
